package com.group11.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group11.user.entity.Enterprise;
import com.group11.user.mapper.EnterpriseMapper;
import com.group11.user.service.EnterpriseService;
import com.group11.user.vo.EnterpriseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {

    @Autowired
    private  EnterpriseMapper enterpriseMapper;

    @Override
    public EnterpriseVo getByUserId(int id) {
        QueryWrapper<Enterprise> userId = new QueryWrapper<Enterprise>()
                .eq("user_id", id)
                .eq("is_deleted", "0");
        Enterprise enterprise = enterpriseMapper.selectOne(userId);
        if (enterprise == null) {
            return null;
        }
        return new EnterpriseVo(enterprise);
    }

    @Override
    public EnterpriseVo getById(int id) {
        QueryWrapper<Enterprise> enterpriseQueryWrapper = new QueryWrapper<Enterprise>()
                .eq("id", id)
                .eq("is_deleted", "0");
        Enterprise enterprise = enterpriseMapper.selectOne(enterpriseQueryWrapper);
        if (enterprise == null) {
            return null;
        }
        return new EnterpriseVo(enterprise);
    }

    @Override
    public List<EnterpriseVo> getAllEnterprise() {
        QueryWrapper<Enterprise> isDeleted = new QueryWrapper<Enterprise>().eq("is_deleted", "0");
        List<Enterprise> enterprises = enterpriseMapper.selectList(isDeleted);
        List<EnterpriseVo> enterpriseVoList = new ArrayList<>();
        enterprises.forEach(enterpriseVo -> {
            enterpriseVoList.add(new EnterpriseVo(enterpriseVo));
        });
        return enterpriseVoList;


    }

    @Override
    public boolean addEnterprise(Enterprise enterprise, int userId) {
        enterprise.setStatus("0");
        enterprise.setIsDeleted("0");
        enterprise.setUserId(userId);
        QueryWrapper<Enterprise> eq = new QueryWrapper<Enterprise>()
                .eq("user_id", userId)
                .eq("is_deleted", "0");
        Enterprise enterprise1 = enterpriseMapper.selectOne(eq);
        if (enterprise1 != null) {
            UpdateWrapper<Enterprise> userId1 = new UpdateWrapper<Enterprise>()
                    .eq("user_id", userId);
            enterpriseMapper.update(enterprise, userId1);
            return true;
        }
        int insert = enterpriseMapper.insert(enterprise);
        return insert > 0;
    }
}
